#include "fstream.h"
#include "http.h"
#include "socket.h"
#include "task.h"
#include "uring_loop.h"
#include <arpa/inet.h>
#include <iostream>
#include <netinet/in.h>
#include <sys/socket.h>
#include <unistd.h>
#include <utility>

co_async::Task<> amain()
{
  co_async::SocketServer serv =
      co_await co_async::SocketServer::CreateServer("127.0.0.1", 8848);
  std::cout << "正在监听 127.0.0.1:8848" << std::endl;
  auto conn = co_await serv.server_accept();
  sockaddr_in paddr;
  socklen_t paddr_len = sizeof(paddr);
  co_async::check_error(
      getpeername(conn.get_fd(), (sockaddr *)&paddr, &paddr_len));
  char peer_ip[INET_ADDRSTRLEN];
  inet_ntop(serv.get_addr().get_family(), &paddr.sin_addr, peer_ip,
            sizeof(peer_ip));
  std::cout << "收到了来自 " << peer_ip << ':' << ntohs(paddr.sin_port)
            << " 的连接" << std::endl;
  co_async::FileStream conns(std::move(conn));
  co_async::HttpRequest req{};
  co_await req.read_from(conns);
  std::cout << req.get_path() << std::endl;
  std::string body = req.get_path();
  for (const auto [key, val] : req.get_queries())
  {
    std::cout << key << ": " << val << std::endl;
    body.append("<p>");
    body.append(key);
    body.append(": ");
    body.append(val);
    body.append("</p>");
  }
  co_async::HttpResponse resp{
      200,
      {{"Content-Type", "text/html; charset=utf-8"}},
      body,
  };
  co_await resp.write_into(conns);
  // co_await co_async::uring_recv(co_async::loop, conn.get_fd(), buf, 0);
  // std::cout << buf << std::endl;
}

int main()
{
  auto t = amain();
  t.get_handle().resume();
  while (!t.get_handle().done())
  {
    co_async::loop.run();
  }
  t.operator co_await().await_resume();
}